/*
 *  Sample C.    Lexical analysis
 */

%{
  #include "symbol.h"
  #include "sintax.h"

  int yywrap(void); 
  int binary();
  void yycomment( char * mat) ;
%}

letter                   [a-zA-Z_]
digit                    [0-9]
letter_or_digit          [a-zA-Z_0-9]
white_space              [ \t\n]
other                    .
%option yylineno
%%

{white_space}+              ;

"/*"                        yycomment("*/");

"int"                       { yylval.ptr = lookUp( yytext );
                              return INT;
                            }
"long"                      { yylval.ptr = lookUp( yytext );
                              return LONG;
                            }
{letter}{letter_or_digit}*  return binary();

{digit}+                    { yylval.ivalue = strtol( yytext, (char**)0, 10);
                              if ( (yylval.ivalue < 32767) &&
                                   (yylval.ivalue >= 0) )
                                return ICONST;
                              else return LCONST; 
                            }
">="                        return GE;
"<="                        return LE;
"=="                        return EQ;
"!="                        return NE;
"+="                        return PE;
"-="                        return ME;
"*="                        return TE;
"/="                        return DE;
"%="                        return RE;
"++"                        return PP;
"--"                        return MM;

{other}                     return yytext[0];

%%

/*
 *  reserved word screener
 */

struct rwtable        /* reserved word table */
{
  char * name;               /* representation */
  int  token;                /* yylex() value  */
} reservedWords[] =          /* sorted */
  {
    "break" , BREAK,
    "continue", CONTINUE,
    "else", ELSE,
    "enum",ENUM,
    "if", IF,
    "return", RETURN,
    "while", WHILE,

  };

int binary()
{
  struct rwtable * low = reservedWords,
                 * high = ( reservedWords - 1 + (sizeof(reservedWords)/sizeof(reservedWords[0]))),
                 * mid = NULL;
  int c;

  while ( low <= high )
  {
    mid = low + ( high - low) / 2;
    if ( ( c = strcmp(mid->name, yytext) ) == 0 )
      return mid->token;
    else if ( c < 0 )
      low = mid + 1;
    else
      high = mid - 1;
  } /* while */

  yylval.ptr = lookUp( yytext );
  return ID;

}/* binary */

void yyerror(char *s){
  printf("%s\n", s);
} /* yyerror */

void yycomment( char * mat) {
  int c;
  char *cp;

  for (cp = mat; *cp != 0; ) {
    c = input();
    if (c == EOF) {
      yyerror("end of file in comment");
      break;
    }
    if (c != *cp++) {
      cp = mat;
      if (c == *cp)
      	cp++;
    }
  } /* for */
} /* yycomment */

int yywrap(void){
  return 1;
}
